<template>
    <div class="w-full h-full box-border flex flex-col overflow-y-hidden">
        <header class="flex-none block">
            <h5 class="h-[76px] flex flex-row items-center text-primary text-2xl font-bold">AI知识库</h5>
            <section class="flex flex-row justify-between items-center pb-[10px]">
                <a-flex align="center" :gap="10">
                    <div v-for="option in stateOptions" :key="option.value"
                        class="flex flex-row items-center h-10 text-nowrap rounded-[6px] border border-solid border-[#CED4DB] text-primary hover:text-theme text-sm px-6 touchable-opacity"
                        :class="formState.state === option.value ? 'bg-theme !text-white' : ''"
                        @click="handleStateChange(option.value)"
                    >
                        {{ option.label }}
                    </div>
                </a-flex>
                <a-flex align="center" :gap="10">
                    <GpSearchInput placeholder="请输入要搜索的内容" class-name="search-input" v-model:value="formState.keyword" @search="refresh()" />
                    <a-button type="primary" size="large" @click="handleAIKnowAction()">
                        <GpFontIcon name="icon-tianjia" />
                        创建知识库
                    </a-button>
                </a-flex>
            </section>
        </header>
        <main class="flex-1 overflow-y-auto py-[10px]">
            <ul class="gap-4 list-cards" v-if="dataSource.length > 0">
                <li class="bg-white relative rounded-xl cursor-pointer flex-none p-5 list-card"
                    v-for="item in dataSource" :key="item.id"
                >
                    <div class="flex flex-row items-center">
                        <div class="flex flex-row justify-center items-center size-[28px] rounded-full flex-none mr-[10px]"
                            :style="{background: colors[0]}"
                        >
                            <img src="/images/ai-knows-card-icon.png" :width="14" :height="14" class="w-[14px] h-[14px] object-cover" />
                        </div>
                        <p class="flex-1 w-0 truncate text-xl font-bold text-primary">{{ item.name }}</p>
                        <a-dropdown placement="bottomRight" :arrow="false">
                            <GpFontIcon name="icon-gengduo1" class="text-[#ACAEB2] !text-xl !leading-5 block ml-7"/>
                            <template #overlay>
                                <a-menu @click="handleMenuAction(item, $event)">
                                    <a-menu-item key="edit">编辑</a-menu-item>
                                    <a-menu-item key="copy">复制</a-menu-item>
                                    <a-menu-item key="remove">删除</a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                    <p class="mt-[14px] text-third text-sm">
                        {{ item.desc && item.desc.length > 40 ? item.desc.slice(0, 40) + '...' : item.desc }}
                    </p>
                    <div class="flex flex-row justify-between items-center mt-5">
                        <section class="flex flex-row items-center">
                            <div class="size-1 rounded-full bg-theme"></div>
                            <div class="text-sm text-primary ml-[10px]">问答数量</div>
                            <div class="text-theme text-sm font-bold ml-2">{{ item.detailCount }}</div>
                        </section>
                        <RouterLink :to="{name: 'AIKnownDetailPage', params:{id: item.id}}" class="size-5 rounded-full !bg-theme/10 flex flex-row justify-center items-center cursor-pointer">
                            <GpFontIcon name="icon-jiantou-you" class="text-theme font-bold" />
                        </RouterLink>
                    </div>
                </li>
            </ul>
            <GpEmpty v-else src="/images/empty-novideo.png" description="暂无内容，快去添加吧~"
            img-class="w-[300px] h-[260px]" class="mt-[160px]" />
        </main>
        <footer class="flex-none flex flex-row items-center justify-end h-15">
            <a-pagination class="!ml-auto" :current="pagination.current" :pageSize="pagination.pageSize"
                show-quick-jumper :total="total" show-less-items show-size-changer @change="handlePaginationChange" :page-size-options="['12','20','28','32']" />
        </footer>
        <!-- 创建/编辑知识库 -->
        <AIKnowActionModal ref="AIKnowActionModalRef" @success="handleAIKnowActionSuccess" />
    </div>
</template>
<script lang="ts" setup>
import { deleteKnowledgeKnowledgedeleteId, postKnowledgeKnowledgecopyId, postKnowledgeKnowledgelist } from '@/api/siderBar/knowledge';
import { type KnowledgeQueryRequestPageSearchRequest, type KnowledgeResult } from '@/api/siderBar/model';
import { useAppStore } from '@/stores';
import type { Exposed as AIKnowActionModalExposed } from './components/AIKnowActionModal/types';
import { message, Modal } from 'ant-design-vue';
import router from '@/router';

defineOptions({
    name: 'AIKnownsPage'
})
definePage({
    name: 'AIKnownsPage',
    meta: {
        title: 'AI知识库',
        isLayout: false
    }
})
enum StateType {
    Team,
    Self
}
type FormState = {
    state: StateType | typeof AllValue
    keyword?: string
}
const appStore = useAppStore()
const { token } = useDesignToken()
const colors = [
    token.value.colorPrimary,
    "#FD9900",
    "#A454FA",
    "#3AD2CA",
    "#FF6B6D",
    "#14B5FF",
    "#68E17A",
    "#FF91BC",
    "#FBD603",
    "#51D6F0"
]
const AIKnowActionModalRef = ref<AIKnowActionModalExposed>()
const stateOptions = ref<IOption<StateType | typeof AllValue>[]>([
    { value: AllValue, label: '全部' },
    { value: StateType.Team, label: '团队' },
    { value: StateType.Self, label: '我的' },
]);
const formState = ref(getInitialState())
const search = computed(() => {
    const { state, keyword } = toValue(formState)
    const params: KnowledgeQueryRequestPageSearchRequest['search'] = {
        name: keyword
    }
    if (state === StateType.Team) params.isTeam = true
    else if (state === StateType.Self) params.isSelf = true
    return params
})
const { dataSource, loading, pagination, refresh, refreshCurrent, total, handlePaginationChange } =
    useTablePaginationRequest(search, postKnowledgeKnowledgelistFetcher, {
        defaultParams: [
            {
                current: 1,
                pageSize: 12,
            }
        ]
    });
function postKnowledgeKnowledgelistFetcher(
    data: KnowledgeQueryRequestPageSearchRequest,
) {
    return postKnowledgeKnowledgelist(data).then(res => normalizePaginationData(res, { current: data.page.pageIndex, pageSize: data.page.pageSize }));
}
function getInitialState(): FormState {
    return {
        state: AllValue
    }
}
function handleStateChange(val: number) {
    if (val === toValue(formState).state) return
    formState.value.state = val
    refresh()
}
async function handleMenuAction(item: KnowledgeResult, {key}: {key: unknown}) {
    if (key === 'edit') {
        handleAIKnowAction(item)
    } else if (key === 'copy') {
        await postKnowledgeKnowledgecopyId(item.id)
        message.success('复制成功')
        refresh()
    } else if (key === 'remove') {
        Modal.confirm({
            title: '确认提示',
            content: '确认要删除吗?',
            async onOk() {
                await deleteKnowledgeKnowledgedeleteId(item.id)
                message.success('删除成功')
                refreshCurrent()
            }
        })
    }
}
useEffectScope(() => {
    watch(loading, () => {
        appStore.toggleLoading(loading.value)
    })
})
function handleAIKnowAction(item?: KnowledgeResult) {
    if (AIKnowActionModalRef.value) {
        AIKnowActionModalRef.value.open(item)
    }
}
function handleAIKnowActionSuccess(mode: "create" | "update", id?: number) {
    if (mode === 'create') router.push({ name: 'AIKnownStartPage', params: { id: id! }})
    else if (mode === 'update') refresh()
}
</script>
<style lang="less" scoped>
.search-input {
    width: 200px;
    height: 40px;
}
.list-cards {
    display: grid;
    grid-template-columns: repeat(2, minmax(414px, 1fr));
}
.list-card {
    width: 100%;
    box-shadow: 0 4px 20px 0 #2e294d0f;
    transition: .15s;
    &:hover {
        transform: translate3d(0, -10px, 10px);
    }
}
@media screen and (min-width: 1024px) {
    .list-cards {
        grid-template-columns: repeat(3, minmax(414px, 1fr));
    }
}
@media screen and (min-width: 1536px) {
    .list-cards {
        grid-template-columns: repeat(4, minmax(414px, 1fr));
    }
}
</style>